package com.assistant.core.modules.sys.domain.user;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Map;

@Component
@ConfigurationProperties("jwt")
@Setter
@Getter
@Slf4j
public class JWTHelper {

    private String secret = "Rjw%lUAML*E41!^0NP&$Q$9E6*Z1VUfw";
    private String issuer = "assistant";

    public String genToken(Token token) {
        return genToken(token.toMap());
    }

    public Token genToken(String token) {
        return Token.fromMap(verifyToken(token));
    }

    /**
     * 产生token
     * @param claims 内容
     * @return token密文
     */
    public String genToken(Map<String, String> claims) {

        //签名算法
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTCreator.Builder builder = JWT.create()
                .withIssuer(issuer)
                .withExpiresAt(Date.from(LocalDateTime.now().plusDays(30).atZone(ZoneId.systemDefault()).toInstant()));
        //相当于将claims存储在token中
        claims.forEach(builder::withClaim);
        return  builder.sign(algorithm);
    }

    /**
     * 校验token
     * @param token token密文
     * @return 解析结果
     * @throws JWTVerificationException
     */
    public Map<String, Claim> verifyToken(String token) throws JWTVerificationException {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer(issuer)
                .build();
        DecodedJWT jwt = verifier.verify(token);
        return jwt.getClaims();
    }
}
